package com.ahrhyj.web.controller.system;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.ahrhyj.common.annotation.Log;
import com.ahrhyj.common.constant.UserConstants;
import com.ahrhyj.common.core.controller.BaseController;
import com.ahrhyj.common.core.domain.AjaxResult;
import com.ahrhyj.common.core.domain.entity.SysRole;
import com.ahrhyj.common.core.domain.entity.SysUser;
import com.ahrhyj.common.core.domain.model.LoginUser;
import com.ahrhyj.common.core.page.TableDataInfo;
import com.ahrhyj.common.core.redis.RedisCache;
import com.ahrhyj.common.enums.BusinessType;
import com.ahrhyj.common.utils.SecurityUtils;
import com.ahrhyj.common.utils.ServletUtils;
import com.ahrhyj.common.utils.StringUtils;
import com.ahrhyj.common.utils.ValidatorUtil;
import com.ahrhyj.common.utils.poi.ExcelUtil;
import com.ahrhyj.framework.web.service.TokenService;
import com.ahrhyj.system.domain.SysUserRole;
import com.ahrhyj.system.service.ISmsLogService;
import com.ahrhyj.system.service.ISysPostService;
import com.ahrhyj.system.service.ISysRoleService;
import com.ahrhyj.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author admin
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISmsLogService smsLogService;

    @Value("${sms.userid}")
    private String userid;
    @Value("${sms.account}")
    private String account;
    @Value("${sms.password}")
    private String password;
    @Value("${sms.sendContent}")
    private String sendContent;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!ValidatorUtil.isUsername(user.getUserName())){
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号格式不正确");
        }
        if (StringUtils.isNotBlank(user.getPhonenumber()) && !ValidatorUtil.isMobile(user.getPhonenumber())){
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码格式不正确");
        }
        if (StringUtils.isNotBlank(user.getEmail()) && !ValidatorUtil.isEmail(user.getEmail())){
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号格式不正确");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotBlank(user.getPhonenumber()) && !ValidatorUtil.isMobile(user.getPhonenumber())){
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码格式不正确");
        }
        if (StringUtils.isNotBlank(user.getEmail()) &&!ValidatorUtil.isEmail(user.getEmail())){
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号格式不正确");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @ApiOperation("修改手机号")
    @PostMapping("/resetPhone")
    public AjaxResult retPhone(@RequestParam String phone, @RequestParam String code){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setUserName(SecurityUtils.getUsername());
        user.setPhonenumber(phone);
        if (!ValidatorUtil.isMobile(user.getPhonenumber())){
            return AjaxResult.error("手机号码格式不正确");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("手机号码已存在");
        }
        int result = smsLogService.validSms(phone, code);
        if(result == 0){
            user.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(userService.updateUser(user));
        }else if(result == -1){
            return AjaxResult.error("亲，验证码不正确，请重新输入");
        }else if(result == -2){
            return AjaxResult.error("请先获取验证码");
        }else if(result == -3){
            return AjaxResult.error("验证码已过期,请重新获取");
        }else{
            return AjaxResult.error("亲，验证码不正确，请重新输入");
        }

    }

    /**
     * 企业用户注册
     */
    @Log(title = "企业用户注册", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StrUtil.isBlank(user.getSmsCode())) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，短信验证码为空");
        }
        String smsCode = redisCache.getCacheObject(user.getPhonenumber());
        if (StrUtil.isBlank(smsCode)) {
            return AjaxResult.error("短信验证码为空或失效，请重新发送");
        } else if (!smsCode.equals(user.getSmsCode())) {
            return AjaxResult.error("短信验证码输入错误，请重新输入");
        }

        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUserType("0");
        userService.insertUser(user);

        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(user.getUserId());
        ur.setRoleId(4L);
        list.add(ur);
        userService.batchUserRole(list);
        return AjaxResult.success(user);
    }

   /* @ResponseBody
    @GetMapping("/sms/code")
    public AjaxResult getSmsCode(@RequestParam("phonenumber") String phonenumber) {
        String smsCode = redisCache.getCacheObject(phonenumber);
        if (StrUtil.isNotBlank(smsCode)) {
            return AjaxResult.error("请勿重复发送短信！");
        }

        boolean isSuccess = false;
        //随机生成验证码
        String code = String.valueOf(new Random().nextInt(999999));
//        try {
//            isSuccess = doSms(phonenumber, code);
//        } catch (Exception e) {
//
//        }
//        if (!isSuccess) {
//            return AjaxResult.error("验证码发送失败或异常");
//        }
        redisCache.setCacheObject(phonenumber, code, 5, TimeUnit.MINUTES);
        return AjaxResult.success();
    }

    public boolean doSms(String receiveUser, String smsCode) {
        boolean isSuccess = false;
        if (StrUtil.isNotBlank(receiveUser) && StrUtil.isNotBlank(smsCode)) {
            try {
                String url = "http://120.27.148.186:8088/sms.aspx?action=send&rt=json&userid=" + userid + "&account=" + account + "&password=" + password + "&mobile=" + receiveUser + "&content=" + sendContent.replace("?", smsCode) + "&sendTime=&extno=";
                String result = HttpUtil.get(url);
                System.out.println("result=" + result);
                isSuccess = true;
            } catch (Exception ex) {

            }

        }
        return isSuccess;
    }

    public static void main(String[] args) {
        String url = "http://120.27.148.186:8088/sms.aspx?action=send&rt=json&userid=1188&account=安徽人和闪信&password=123456&mobile=13275757551&content=【政企互通管理平台】验证码111111，用于注册。泄露有风险，如非本人操作，请忽略本条短信，验证码有效期5分钟。&sendTime=&extno=";
        String result = HttpUtil.get(url);
        System.out.println("result=" + result);
    }*/
}
